//
//  AppDelegate.swift
//  MYDoctor
//
//  Created by 小火科技 on 2024/2/27.
//

import UIKit
import IQKeyboardManagerSwift
import BaiduMapAPI_Base
import BMKLocationKit
//import UMCommon

@main
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    var window: UIWindow?
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.resignOnTouchOutside = true
        
        injectCodeOnlyOnce()
        _ = CXDownloadManager.shared
        MYGDownloadManager.shared.getCacheData()
        MYGUploadManager.shared.getCacheData()
        
        let manager = BMKMapManager()
        if !manager.start(mapAK, generalDelegate: self) {
            print("百度地图引擎启动失败")
        }
        BMKMapManager.setAgreePrivacy(true)
        BMKLocationAuth.sharedInstance().checkPermision(withKey: mapAK, authDelegate: self)
        BMKLocationAuth.sharedInstance().setAgreePrivacy(true)
        
        if #available(iOS 15.0, *) {
            UITableView.appearance().sectionHeaderTopPadding = 0
        }
        
        
        window = UIWindow(frame: UIScreen.main.bounds)
        
        if MYGUserManager.isLogin {
            let vc = MYGTabBarController()
            window?.rootViewController = vc
            MYGSocketManager.shared.connect()
            let isSuc = MYGUserManager.isDoctorInfComplete
            MYGUserManager.isDoctorInfComplete = isSuc
        } else {
            let vc = MYGNavigationController(rootViewController: MYGRegisterController())
            window?.rootViewController = vc
        }
        
        window?.makeKeyAndVisible()
        
//        DispatchQueue.main.asyncAfter(delay: 3) { [self] in
//            configUM()
//        }
//        
        return true
    }
    
    //友盟
    func configUM() {
        
//        print("当前版本号为\(String(describing: UMSocialGlobal.umSocialSDKVersion()))")
//        
//        UMConfigure.initWithAppkey("6671411a940d5a4c4970c2fc", channel: "App Store")
//
//        UMSocialGlobal.shareInstance().isUsingHttpsWhenShareContent = false
//        UMSocialGlobal.shareInstance().universalLinkDic = [UMSocialPlatformType.wechatSession :"https://yz-server-dev.medataplus.com/mydoctor/"]
//
//        UMSocialManager.default().setPlaform(.wechatSession, appKey: "wx2de38e5ad9053edc", appSecret: "cfdda65d7d02d7ef1f880456819880b6", redirectURL: "https://yz-server-dev.medataplus.com/mydoctor/")
//        
//        UMSocialManager.default().openLog(true)
//        UMConfigure.setLogEnabled(true)
//      
//        print(UMSocialManager.default().isSupport(UMSocialPlatformType.wechatSession))
//        UMSocialManager.default().setPlaform(UMSocialPlatformType.QQ, appKey: "1105821097", appSecret: "3baf1193c85774b3fd9d18447d76cab0", redirectURL: "http://mobile.umeng.com/social")
    }
    func injectCodeOnlyOnce() {
        let ud = UserDefaults.standard
        let onceKey = "InjectCodeOnlyOnceKey"
        if !ud.bool(forKey: onceKey) {
            ud.set(30, forKey: CXDownloadConfig.maxConcurrentCountKey)
            ud.set(false, forKey: CXDownloadConfig.allowsCellularAccessKey)
            ud.set(true, forKey: onceKey)
            ud.synchronize()
        }
    }
    
    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
        .allButUpsideDown
    }
    
    var backgroundTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0)
    
    func applicationDidEnterBackground(_ application: UIApplication) {
        backgroundTask = application.beginBackgroundTask(expirationHandler: {
            // 如果在10分钟内没有完成任务，系统会终止应用程序
            self.endBackgroundTask()
        })
        
        // 在这里可以添加你的WebSocket保活逻辑
        // 比如重连WebSocket，或者保持心跳
        
    }
    
    func applicationWillEnterForeground(_ application: UIApplication) {
        // 当应用程序回到前台时，结束后台任务
        endBackgroundTask()
        if MYGUserManager.isLogin {
            MYGSocketManager.shared.reContent()
        }
    }
    
    func endBackgroundTask() {
        if backgroundTask != UIBackgroundTaskIdentifier.invalid {
            UIApplication.shared.endBackgroundTask(backgroundTask)
            backgroundTask = UIBackgroundTaskIdentifier.invalid
        }
    }
    
}

extension AppDelegate: BMKGeneralDelegate, BMKLocationAuthDelegate {
    
}
